import axios from "axios";
import { useUserStore } from "@/store/modules/user";
import { showNotify,showToast } from "vant";

export const request = axios.create({
  baseURL: "/api",
  timeout: 1000 * 10,
  withCredentials: true,
});

request.interceptors.request.use((config) => {
  // const userStore = useUserStore();

  // if (userStore.token) {
  //   config.headers.Authorization = `Bearer ${userStore.token}`;
  // }

  if (config.method.toLocaleUpperCase() === "GET") {
    config.headers.setContentType('application/x-www-form-urlencoded')
  }
  return config;
});

request.interceptors.response.use(
  (response) => {
    if (!!!response.data) {
      showNotify({ type: "danger", message: "系统错误！" });
    } else {
      return response.data;
    }
    return Promise.reject(response);
  },
  (error) => {
    // 处理 http 错误响应码
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error

    // 请求超时 && 网络错误单独判断，没有 response
    if (error.message.indexOf("timeout") !== -1)
      showToast.error("请求超时！请您稍后重试");
    if (error.message.indexOf("Network Error") !== -1)
      showToast.error("网络错误！请您稍后重试");
    // 根据服务器响应的错误状态码，做不同的处理
    if (error.response) checkStatus(error.response.status);
    // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
    if (!window.navigator.onLine) router.replace("/500");

    return Promise.reject(error);
  }
);

const checkStatus = (status) => {
  switch (status) {
    case 400:
      showToast.error("请求失败！请您稍后重试");
      break;
    case 401:
      showToast.error("登录失效！请您重新登录");
      break;
    case 403:
      showToast.error("当前账号无权限访问！");
      break;
    case 404:
      showToast.error("你所访问的资源不存在！");
      break;
    case 405:
      showToast.error("请求方式错误！请您稍后重试");
      break;
    case 408:
      showToast.error("请求超时！请您稍后重试");
      break;
    case 500:
      showToast.error("服务异常！");
      break;
    case 502:
      showToast.error("网关错误！");
      break;
    case 503:
      showToast.error("服务不可用！");
      break;
    case 504:
      showToast.error("网关超时！");
      break;
    default:
      showToast.error("请求失败！");
  }
};
